package com.zx.service;

import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;


@CacheConfig(cacheNames = "user") // 所有@Cacheable的value值就都为user
@Service
public class UserService {

    @Cacheable(key = "#id") // 指定key
    public User getUser1(Integer id) {

        System.out.println("---- get user ----");

        return new User(id, "zhangsan" + id, 10 + id);

    }
    @Cacheable // 使用默认key策略
    public String getUser2(Integer id, String name) {
        return new User(id, "zhangsan" + id, 10 + id).toString();
    }

    @Cacheable(keyGenerator = "keyGenerator") // 手动指定key策略
    public User getUser3(Integer id, String name) {
        return new User(id, "zhangsan" + id, 10 + id);
    }


    @CachePut(key = "#user.id")
    public User saveUser(User user) {

        System.out.println("---- save user ----");

        return user;
    }

    @Caching(put ={@CachePut(key = "\"id_\" + #user.id"),
            @CachePut(value="name_", key = "#user.name")})
    public User saveAll(User user) {

        System.out.println("---- save user ----");

        return user;
    }

    @CacheEvict(key = "#id")
    public void deleteUser(Integer id) {

        System.out.println("---- delete user ----");
    }
}

